import { notification } from "ant-design-vue"
import axios, { type AxiosInstance } from "axios"
import type { App } from "vue"

// 创建 axios 实例
export const request = axios.create({
  // API 请求的默认前缀
  baseURL: import.meta.env.VITE_PROXY_HTTP_API,
  timeout: 6000
})

// 异常拦截处理器
const errorHandler = (error: any) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }

    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)



// 插件
export function VueAxios(app: App): void {
  if (app.config.globalProperties.$axios != null) {
    return
  }
  app.config.globalProperties.$axios = request
}
export function GetCurrentSocket(): AxiosInstance {
  return getCurrentInstance()?.appContext.config.globalProperties.$axios
}

export function get<TRequest, TResponse>(api: string, data: TRequest) {
  return request.get<TRequest, TResponse>(api, { params: data })
}


export function postJson<TRequest, TResponse>(api: string, data: TRequest) {
  return request.post<TRequest, TResponse>(api, JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

export function putJson<TRequest, TResponse>(api: string, data: TRequest) {
  return request.put<TRequest, TResponse>(api, JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

export function deleteJson<TRequest, TResponse>(api: string, data: TRequest) {
  return request.delete<TRequest, TResponse>(api, {
    data: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

const all = axios.all
export { all }
